﻿#include "logqueue.h"

#include <QTextStream>
#include <QDebug>

#ifndef TEST_PATH
#include "MyHelper.h"
#endif

bool LogQueue::loadLog(QDateTime beginDateTime, const QDateTime &endDateTime, const LogType type)
{
    clear();

    QFile logFile;
    while (beginDateTime <= endDateTime) {
#ifdef TEST_PATH
        logFile.setFileName(QString("%1/%2.log").arg(TEST_PATH, beginDateTime.toString("yyyyMMdd_HH")));
#else
        logFile.setFileName(QString("%1/%2.log").arg(AppPath, beginDateTime.toString("yyyyMMdd_HH")));
#endif // TEST_PATH

        if (!logFile.exists()) {
            qDebug() << logFile.fileName() << " no exist";
            beginDateTime = beginDateTime.addSecs(3600); // 增加一小时
            continue;
        }

        if (!logFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qDebug() << logFile.fileName() << " can not read";
            beginDateTime = beginDateTime.addSecs(3600); // 增加一小时
            logFile.close();
            continue;
        }

        QTextStream in(&logFile);
        while (!in.atEnd()) {
            QString logStr = in.readLine();
            auto logInfoList = logStr.split(' ');
            if (logStr.isEmpty() || !judgeType(logInfoList, type)) continue;

            logInfoList = getFormatLogTxt(logInfoList);
            std::tuple<QDate, QTime, QString, QString> log = std::make_tuple(QDate::fromString(logInfoList.at(0), "yyyy-MM-dd"),
                                                                             QTime::fromString(logInfoList.at(1), "HH:mm:ss"),
                                                                             logInfoList.at(2),
                                                                             logInfoList.at(3));
            //logWork(logStr, log);
            m_logQueue.push(log);
        }
        beginDateTime = beginDateTime.addSecs(3600);

        logFile.close();
    }

    emit updateTable();
    return true;
}

bool LogQueue::judgeType(const QStringList &logStrList, const LogType type)
{
    if (logStrList.size() < 4)
        return false;

    switch (type) {
    case LogType_SoftRun: return logStrList.at(3).startsWith("软");
    case LogType_Device: return logStrList.at(3).startsWith("接收机");
    case LogType_Alarm: return (logStrList.at(2).compare("ERROR") == 0);
    case LogType_User : return logStrList.at(3).startsWith("用户");
        // 背景迹线无法获取标识字符串, 故非以上类型的日志, 均为背景迹线
    case LogType_BGTrace: return (logStrList.at(3).contains("采集"));
    }

    return false;
}

QStringList LogQueue::getFormatLogTxt(const QStringList &logStrList) const
{
    if (logStrList.size() <= 4) {
        return logStrList;
    }

    auto tmpTxt = logStrList.mid(3).join(' ');
    return QStringList({logStrList[0], logStrList[1], logStrList[2], tmpTxt});
}
